#include <QMap>
#include <QTimer>
#include <QDebug>
#include "agentpush.h"
#include "Agent/getsetfield.h"

AgentPush::AgentPush(QObject *parent) :
    QObject(parent)
{
    timerIntervalMilliSecs=60000;//1分钟一次
    ttlMax=6;
    timerForTTL.start(timerIntervalMilliSecs);
    connect(&timerForTTL,SIGNAL(timeout()),this,SLOT(slotTimerTTL()));

}

void AgentPush::newSubscriber(QByteArray parSNOfReq,
                              QByteArray baIPPort, QByteArray origRequestpacket)
{
    sNOfReq=parSNOfReq;
    mapIPPortTTL.insert(baIPPort,ttlMax);
    mapIPPortReqPacket.insertMulti(baIPPort,origRequestpacket);
}

QMap <QByteArray,QByteArray> AgentPush::getMapIPPortReqPacket()
{
    return mapIPPortReqPacket;
}

void AgentPush::pushToApps(QByteArray packet)
{
    QMapIterator<QByteArray,qint16> i(mapIPPortTTL);  //遍历整个map
    while (i.hasNext())
    {
        i.next();
        QByteArray baIPPort=i.key();
        bool ok;
        emit sigSendDataToApp(GetSetField::setSN(packet,sNOfReq),baIPPort.split(':').at(0),
           baIPPort.split(':').at(1).toUInt(&ok,10));
    }

}

void AgentPush::slotTimerTTL()
{
    QMapIterator<QByteArray,qint16> i(mapIPPortTTL);  //遍历整个map
    while (i.hasNext())
    {
        i.next();
        if(i.value()<=0) //该TTL过期
        {
            mapIPPortTTL.remove(i.key()); //作相应处理
            mapIPPortReqPacket.remove(i.key());
        }
        else
            mapIPPortTTL.insert(i.key(),i.value()-1);
    }

}
